package com.lmk.mkcc.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.lmk.mkcc.constants.CommonConstants;
import com.lmk.mkcc.domain.*;
import com.lmk.mkcc.dto.PhoneRegisterDto;
import com.lmk.mkcc.enums.GlobalErrorCode;
import com.lmk.mkcc.feign.LoginService;
import com.lmk.mkcc.mapper.UserMapper;
import com.lmk.mkcc.result.JSONResult;
import com.lmk.mkcc.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.lmk.mkcc.util.AssertUtil;
import com.lmk.mkcc.util.BitStatesUtils;
import com.lmk.mkcc.util.StrUtils;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.util.Date;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author kun
 * @since 2022-09-23
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Autowired
    private LoginService loginService;
    @Autowired
    private IUserAccountService iUserAccountService;
    @Autowired
    private IUserBaseInfoService iUserBaseInfoService;
    @Autowired
    private IUserRegisterService registerService;
    @Autowired
    private IUserIntegralLogService userIntegralLogService;
    @Autowired
    private IUserGrowthService userGrowthService;
    @Autowired
    private IUserGrowLogService userGrowLogService;
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void phoneRegister(PhoneRegisterDto phoneRegisterDto) {
        // 1.获取前端传入参数
        String mobile = phoneRegisterDto.getMobile();
        String smsCode = phoneRegisterDto.getSmsCode();
        String password = phoneRegisterDto.getPassword();
        Integer regChannel = phoneRegisterDto.getRegChannel();
        // 2.判断验证码是否过期
        String format = String.format(CommonConstants.Register_PHONE_PREFIX, mobile);
        Object o = redisTemplate.opsForValue().get(format);
        String obj = o.toString();
        // 断言不为null，若为null，证明验证码已经过期
        AssertUtil.isNotNull(obj, GlobalErrorCode.CODE_EXPIRED_ERROR);
        // 断言前端传入的验证码与redis中保存的验证码相等
        String s = obj.split(":")[0];
        AssertUtil.isEquals(smsCode,s,GlobalErrorCode.CODE_MISMATCH_ERROR);
        // 判断用户手机是否注册过
        User user = selectByMobile(mobile);
        AssertUtil.isNull(user,GlobalErrorCode.USER_EXIST_ERROR);
        // 先保存到t_login表
        JSONResult jsonResult = addLogin(phoneRegisterDto);
        //int i = 3/0;
        // 断言保存成功,返回一个loginId
        AssertUtil.isTrue(jsonResult.isSuccess(),GlobalErrorCode.FUSE_ERROR);
        // 获取data中传入的data--loginId,并将他转化为long类型
        Object data = jsonResult.getData();
        Long loginId = Long.valueOf(data.toString());
        // 将数据保存到t_user、t_user_account、t_user_base_info
        User user1 = addUser(loginId,phoneRegisterDto);
        initUserAccount(user1.getId());
        initUserBaseInfo(user1.getId(), phoneRegisterDto);

        if (phoneRegisterDto.getRegisterCode()!= ""){
            // 先通过code获取该用户的id
            UserRegister userRegister = registerService.getUserIdByCode(phoneRegisterDto.getRegisterCode());
            // 根据userRegister的id来查询该用户的积分
            UserBaseInfo userBaseInfo =  iUserBaseInfoService.getUserById(userRegister.getUserId());
            // 为该用户添加积分
            userBaseInfo.setGrowScore(userBaseInfo.getGrowScore()+10);
            // 设置修改时间
            userBaseInfo.setUpdateTime(System.currentTimeMillis());
            // 修改用户积分信息
            iUserBaseInfoService.updateById(userBaseInfo);
            // 重新为该用户生成推荐码
            userRegister.setCode(StrUtils.getComplexRandomString(4));
            registerService.updateById(userRegister);


            // 为推荐用户添加成长值
            if (userGrowthService.getByUserId(userRegister.getUserId()) == null){
                UserGrowth userGrowth = new UserGrowth();
                userGrowth.setGrowthValue(10);
                userGrowth.setUserId(userRegister.getUserId());
                userGrowth.setGrade("⻘铜");
                userGrowth.setDetail("不享受折扣");

            }else {
                UserGrowth growth = userGrowthService.getByUserId(userRegister.getUserId());
                growth.setGrowthValue(growth.getGrowthValue()+10);
                if ((growth.getGrowthValue()+10)<=99){
                    growth.setGrade("⻘铜");
                    growth.setDetail("不享受折扣");
                }else if((growth.getGrowthValue()+10-100)<=99){
                    growth.setGrade("白银");
                    growth.setDetail("可享受 9.8折优惠");
                }else if((growth.getGrowthValue()+10-300)<=299){
                    growth.setGrade("黄金");
                    growth.setDetail("可享受 9.5 折优惠");
                }else if ((growth.getGrowthValue()+10-600)<=399){
                    growth.setGrade("⽩⾦");
                    growth.setDetail("可享受 9 折优惠");
                }else if((growth.getGrowthValue()+10-1000)<=499){
                    growth.setGrade("钻石");
                    growth.setDetail("可享受 8.8 折优惠");
                }else if((growth.getGrowthValue()+10-1500)<=999){
                    growth.setGrade("大师");
                    growth.setDetail("可享受 8.5 折优惠");
                }else if((growth.getGrowthValue()+10)>=2500){
                    growth.setGrade("王者");
                    growth.setDetail("可享受 8 折优惠");
                }
                userGrowthService.updateById(growth);
            }
            // 保存到成长日志
            UserGrowLog userGrowLog = new UserGrowLog();
            userGrowLog.setCreateTime(System.currentTimeMillis());
            userGrowLog.setUserId(userRegister.getUserId());
            userGrowLog.setScore(10);
            userGrowLog.setFromReason("推荐送积分");
            userGrowLog.setRemark("积分大放送");
            userGrowLogService.insert(userGrowLog);

            // 保存到积分日志表
            UserIntegralLog userIntegralLog = new UserIntegralLog();
            userIntegralLog.setCreateTime(new Date());
            userIntegralLog.setIntegralCount(userBaseInfo.getGrowScore()+10);
            userIntegralLog.setType("积分添加");
            userIntegralLog.setUserId(userRegister.getUserId());
            userIntegralLogService.insert(userIntegralLog);

        }
        // 为用户生成邀请码
        String complexRandomString = StrUtils.getComplexRandomString(4);
        // 将邀请码保存到t_user_register表中
        registerService.save(complexRandomString,user1.getId());
        // 保存到usergrowth表

    }

    private void initUserAccount(Long id) {
        UserAccount userAccount = new UserAccount();
        userAccount.setId(id);
        userAccount.setPassword("111111");
        userAccount.setCreateTime(new Date().getTime());
        iUserAccountService.insert(userAccount);
    }

    private void initUserBaseInfo(Long id, PhoneRegisterDto phoneRegisterDto) {
        Integer regChannel = phoneRegisterDto.getRegChannel();
        UserBaseInfo userBaseInfo = new UserBaseInfo();
        userBaseInfo.setId(id);
        userBaseInfo.setCreateTime(new Date().getTime());
        userBaseInfo.setRegChannel(regChannel);
        iUserBaseInfoService.insert(userBaseInfo);
    }




    private User addUser(Long loginId, PhoneRegisterDto phoneRegisterDto) {
        User user1 = new User();
        user1.setLoginId(loginId);
        user1.setPhone(phoneRegisterDto.getMobile());
        user1.setCreateTime(new Date().getTime());
        user1.setNickName(phoneRegisterDto.getMobile());

        long state = BitStatesUtils.addState(BitStatesUtils.OP_ACTIVED, BitStatesUtils.OP_REGISTED);
        long state1 = BitStatesUtils.addState(BitStatesUtils.OP_AUTHED_PHONE, state);
        user1.setBitState(state1);
        insert(user1);
        return  user1;


    }

    // 添加到t_login表
    private JSONResult addLogin(PhoneRegisterDto phoneRegisterDto) {
        String password = phoneRegisterDto.getPassword();
        String mobile = phoneRegisterDto.getMobile();
        Login login = new Login();
        login.setUsername(mobile);
        login.setPassword(password);
        login.setType(0);
        login.setEnabled(true);
        JSONResult jsonResult = loginService.saveOrUpdate(login);
        return jsonResult;
    }
    // 查询用户是否已经注册
    private User selectByMobile(String mobile) {
        // 创建包装器
        EntityWrapper<User> wrapper = new EntityWrapper<>();
        // 映射
        wrapper.eq("phone","mobile");
        return selectOne(wrapper);
    }
}
